package com.leetao.ifkiller.core.impl;

import com.leetao.ifkiller.core.CommandExecutor;
import com.leetao.ifkiller.core.CommandIssuer;
import com.leetao.ifkiller.domain.Command;
import com.leetao.ifkiller.domain.PredicatePro;

import java.util.LinkedList;
import java.util.List;

/**
 * 默认命令执行器
 *
 * @author 菅江晖
 * @date 2021/6/11 - 0:47
 */
public class CommandExecutorImpl<T> implements CommandExecutor<T> {
    private final CommandIssuer<T> leader;
    private final List<Command<T>> commands = new LinkedList<>();

    public CommandExecutorImpl(CommandIssuer<T> leader) {
        this.leader = leader;
    }

    @Override
    public CommandExecutor<T> execute(Command<T> command) {
        commands.add(command);
        execute0(command, true);
        return this;
    }

    public void execute0(Command<T> command, boolean now) {
        //检查条件是否允许执行
        for (PredicatePro<T> condition : command.getConditions()) {
            if (!condition.getPredicate().test(leader.clientele())) {
                return;
            }
        }

        //执行命令
       //  System.out.println("execute: " + command.showCommand());
        command.getConsumerPro().getConsumer().accept(leader.clientele());
    }
}
